package server.simple100;

import org.junit.Test;

/***
 * 203. 移除链表元素
 */
public class LeetCode203 {


    @Test
    public void test() {
        ListNode node = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(1);
        ListNode node4 = new ListNode(1);
        node.next = node2;
        node2.next = node3;
        node3.next = node4;
        System.out.println(removeElements(node, 1));
    }

    public ListNode removeElements(ListNode head, int val) {
        ListNode newHead = null;
        // 最后一个节点
        ListNode lastNode = null;
        while (head != null) {
            if (head.val != val) {
                if (newHead == null) {
                    newHead = new ListNode(head.val);
                    lastNode = newHead;
                } else {
                    lastNode.next = new ListNode(head.val);
                    lastNode = lastNode.next;
                }
            }
            head = head.next;
        }
        return newHead;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
